<template>
  <div>
    <el-row>
      <el-col :span="12" class="center">
        <div id="pb" ref="pb" style=""
          @drop="drop($event)"
          @dragover.prevent="allowDrop($event)"
          @dragenter.prevent="onDragEnter($event)"
          @onmousedown="onMouseDown($event)">
          <!--<canvas />-->
        </div>
        <div class="btn-groups">
          <el-button size="small" @click="reset">重置</el-button>
          <el-button size="small" @click="undo" >撤销</el-button>
          <el-button size="small" @click="redo" :disabled="canRedo">重做</el-button>
          <el-button size="small" @click="saveCurrentFrame">保存</el-button>
        </div>
        <div>
          <el-checkbox v-model="playContinue">连续播放</el-checkbox>
        </div>
      </el-col>
      <el-col :span="12">
        <!--功能编辑 -->
        <div v-if="isFunctional">
          <h2 class="board-title"> 功能 </h2>
          <el-row>
            <el-col :span="3" draggable="true"
              @dragstart.prevent="onDragStart($event, 'offense', attackColor)"
              @dragend="onDragEnd($event)"
              class="pt15">
              <img draggable="true"
                  @dragstart="onDragStart($event, 'offense', attackColor)"
                  @dragend="onDragEnd($event)"
                  src="/static/images/board/circle.svg">
            </el-col>
            <el-col :span="21">
              <el-row class="board-slider">
                <el-col :span="3" class="board-text">进攻</el-col>
                <el-col :span="21" class="the-slider">
                  <el-slider v-model="attackNum" :min="1" :max="10"></el-slider>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="3" class="relative drag-triangle pt15"
              draggable="true"
              @dragstart.prevent="onDragStart($event, 'defense', defenseColor)"
              @dragend="onDragEnd($event)">
                <img draggable="true"
                  @dragstart="onDragStart($event, 'defense', defenseColor)"
                  @dragend="onDragEnd($event)"
                  src="/static/images/board/triangle.svg">
            </el-col>
            <el-col :span="21">
              <el-row class="board-slider">
                <el-col :span="3" class="board-text">防守</el-col>
                <el-col :span="21" class="the-slider">
                  <el-slider v-model="defenseNum" :min="1" :max="10"></el-slider>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row class="ball-area">
            <el-col :span="3"  class="pt15" draggable="true"
              @dragstart="onDragStart($event,'ball', ballColor)"
              @dragend="onDragEnd($event)">
              <img src="/static/images/board/basketball.svg" v-show="ballNum ==1"
                @dragstart="onDragStart($event,'ball', ballColor)"
                @dragend="onDragEnd($event)">
              <img src="/static/images/board/instrument.svg" v-show="ballNum ==2"
                @dragstart="onDragStart($event,'obstacle', ballColor)"
                @dragend="onDragEnd($event)">
            </el-col>
            <el-col :span="21">
              <el-row class="board-slider">
                <el-col :span="3" class="board-text" >{{ballNum ==1 ? '篮球': '障碍物'}}</el-col>
                <el-col :span="21" class="the-slider">
                  <el-slider v-model="ballNum" :min="1" :max="2"></el-slider>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <h2 class="board-title">移动轨迹</h2>
          <el-row :gutter="16" style="margin-bottom:20px;" :key="Math.random()">
            <el-col
              v-for="(item,index) in lineTypeList"
              :key="item.url"
              :span-percent="20">
              <div class="board-line"
                :class="{selected: item.selected}"
                @click="selectLineType(index)">
                <span :style="{background: `url(${item.selected ? item.h_url : item.url})`}">
                </span>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="16" >
            <el-col
              v-for="(item,index) in lineList"
              :key="item.url"
              :span-percent="20">
              <div class="board-line"
                :class="{selected: item.selected}"
                @click="selectLine(index)">
                <span :style="{background: `url(${item.selected ? item.h_url : item.url})`}">
                </span>
              </div>
            </el-col>
          </el-row>
          <!--颜色选择器-->
          <el-row style="margin: 30px 0 40px;">
            <el-col  class="color-txt attack-color" :span="4">颜色</el-col>
            <el-col  class="attack attack-color" :span="20">
              <el-color-picker v-model="lineColor"></el-color-picker>
              <el-button @click="handleDeleteItem" size="small"
                :disabled="playbook && !playbook.selectedItem">
                <i class="el-icon-delete"></i>删除
              </el-button>
            </el-col>
          </el-row>
          <!--
          <h2 class="board-title">插入内容</h2>
          <div>
            <el-button>文字</el-button>
            <el-button>自定义图形 </el-button>
            <el-button>图形</el-button>
          </div>
          -->
        </div>

        <!--图形选择 -->
        <div v-else> 
          <h2 class="board-title"> 图形编辑 </h2>
          <el-row class="board-gragh">
            <el-col
              class="graph-item" 
              :span="8" 
              v-for="(item,index) in graghList"
              :key="item.html"
              :class="{'gragh-select':item.selected}">
              <i class="icon iconfont" 
                :style="{color: graphColor}" 
                shape="1" 
                @click="updateShape(item.id)" v-html="item.html"></i>
            </el-col>
          </el-row>

          <el-row class="color-set">
            <el-col class="color-label" :span="5" :offset="2">
              字体颜色
            </el-col>
            <el-col :span="15">
              <el-color-picker v-model="fontColor" />
            </el-col>
          </el-row>
          <el-row >
            <el-col class="color-label" :span="5" :offset="2">图形颜色</el-col>
            <el-col :span="15">
              <el-color-picker v-model="graphColor"></el-color-picker>
            </el-col>
          </el-row>
          <div class="center" style="margin:50px 0 20px;">
            <el-button @click="cancelSeleted">取消</el-button>
            <el-button type="primary" @click="saveSeletedItem">保存 </el-button>            
          </div>
          <div class="center">
          <el-button @click="handleDeleteItem">删除</el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <div class="board-steps">
      <h2 >步骤</h2>
      <el-row>
        <el-col :span="18">
          <div class="board-scroll">
            <!--<el-scrollbar wrap-class="board-wrapper" >
            </el-scrollbar>-->
            <BoardStepBar
              :frameList="frameList"
              :playbook="playbook"
              @switch="switchFrame"
              @delete="DeleteFrame">
            </BoardStepBar>
          </div>
        </el-col>
        <el-col :span="6" style="padding-left: 12px;">
          <div class="add-board" @click="insertFrame"
            :class="{
              'tall': playbook && playbook.frames && playbook.frames.length >4,
              'no-scroll': playbook && playbook.frames && playbook.frames.length <=4,
              'half':playbook && playbook.type && playbook.type.includes('half')
            }">
            <i class="el-icon-plus"></i>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="center">
      <el-button type="primary" size="small" @click="handleSaveSteps">保存步骤</el-button>
    </div>
  </div>
</template>
<script>
import debounce from 'lodash.debounce'
import api from 'api/tactics'
import {BasketBallPlaybook} from 'utils/playbook'
import BoardStepBar from './components/BoradStepBar'
import {getCanvasPos, getStyles} from 'utils' // eslint-disable-line

export default{
  props: {
    sportType: [String, Number],
    tacticTypeId: [String, Number],
    tacticId: [String, Number],
    currentTab: String
  },
  components: {
    BoardStepBar
  },
  created () {
  },
  mounted () {
    this.$nextTick(function () {
      let pbdom = this.$refs['pb']
      this.playbook = new BasketBallPlaybook(pbdom)
      this.playbook.width = '400px'
      this.drawBg()
      // window.self = this
      let that = this
      document.onkeydown = function (e) {
        if (e.code === 'Delete' || e.keyCode === 46 || e.key === 'Delete') {
          if (that.playbook && that.playbook.selectedItem) {
            that.playbook.remove(that.playbook.selectedItem)
            that.playbook.selectedItem = null
            that.playbook.update()
            that.resetLineType()
            if (!that.isFunctional) {
              that.isFunctional = true
            }
          }
        }
      }
      let scrollbar = document.getElementsByClassName('board-scroll-bar')[0]
      scrollbar.addEventListener('scroll', debounce((e) => {
        this.scrollNow = scrollbar.scrollLeft / scrollbar.scrollWidth
      }, 200))
    })
  },
  updated () {
  },
  computed: {
    tacticsInfo () {
      return this.$store.getters.tactics_info
    }
  },
  watch: {
    lineColor (val, oldVal) {
      // 更新线段颜色
      if (this.playbook.selectedItem) {
        this.playbook.selectedItem.color = val
        this.playbook.update()
      }
    },
    selectedLine (val, oldVal) {
      this.updateLine()
    },
    selectedLineType (val, oldVal) {
      this.updateLine()
    },
    'tacticsInfo.id' (id) {
      if (id) {
        let val = this.tacticsInfo
        // console.log('获取到content:', val)
        this.playbook.clear()
        let hasFrame = val.frames || val.sprites
        let type = val.type
        this.drawBg(type, hasFrame)
        this.lastStep = 0
        this.drawFrameList(hasFrame)
      }
    },
    scrollNow (val, oldVal) {
      if (val > oldVal && this.lastStep < this.playbook.frames.length) { // 向右滑动
        this.drawStepFrame(this.lastStep, this.lastStep + this.stepLength)
      }
    },
    tacticId (val, oldVal) {
    },
    currentTab (val, oldVal) {
      if (val !== oldVal && val === 'edit') {
        let hasFrame = this.tacticsInfo.frames || this.tacticsInfo.sprites
        let type = this.tacticsInfo.type || this.playbook.type
        if (hasFrame) {
          this.playbook.deserialize(this.tacticsInfo)
          this.playbook.update()
          this.lastStep = 0
          this.drawFrameList(hasFrame)
        } else {
          this.drawBg(type, hasFrame)
        }
        if (this.hasReset) {
          this.drawBg(type, hasFrame)
          this.lastStep = 0
          this.drawFrameList(hasFrame)
          this.hasReset = false
        }
      }
    }
  },
  data () {
    let playbook
    let lineTypeList = [1, 2, 3, 4, 5].map(item => {
      return {
        id: item,
        url: `/static/images/board/black/${item}.png`,
        h_url: `/static/images/board/white/${item}.png`,
        selected: 0
      }
    })
    let graghList = ['&#xe664;', '&#xe66c;', '&#xe666;', '&#xe668;', '&#xe663;', '&#xe66b;'].map((item, index) => {
      return {
        html: item,
        id: index + 1,
        selected: 0
      }
    })
    let scrollPercent
    return {
      hasReset: false,
      scrollPercent,
      scrollNow: 0,
      graghList,
      frameWidth: 120,
      selectedLineType: {},
      selectedLine: {},
      graphColor: '#4eca60',
      fontColor: '#fff',
      lineColor: '#000',
      attackColor: '#4eca60',
      defenseColor: '#4ec5fe',
      ballColor: '#f38e32',
      isFunctional: true, // true:显示功能区域，false: 显示图形选择区域
      playContinue: true,
      attackNum: 1,
      defenseNum: 1,
      ballNum: 1,
      lineTypeList,
      lineList: [
        {
          type: 'l',
          h_url: '/static/images/board/white/6.png',
          url: '/static/images/board/black/6.png',
          selected: 1
        },
        {
          type: 'c',
          h_url: '/static/images/board/white/7.png',
          url: '/static/images/board/black/7.png',
          selected: 0
        }
      ],
      dragedObj: {},
      playbook,
      transformScale: 0.8,
      tacticName: '',
      canRedo: false,
      canUndo: false,
      frameList: [],
      lastStep: 0,
      stepLength: 30
    }
  },
  methods: {
    /*
     type: 场地类型 1：全场，2：上半场，3：下半场
     hasFrame: 是否保存有帧
    */
    drawBg (type, hasFrame) {
      this.selectedLine = this.lineList[0]
      let self = this
      let pd = this.$refs['pb']
      let pbdiv = pd.children[0]
      if (type === 2 || type === 'half-up') {
        this.playbook.type = 'half-up'
        pbdiv.style.height = '500px'
      } else if (type === 3 || type === 'half-down') {
        this.playbook.type = 'half-down'
        pbdiv.style.height = '500px'
      } else {
        this.playbook.type = 'full'
        this.playbook.height = '700px'
      }
      this.playbook.scale = 0.8
      this.playbook.history = true
      this.playbook.designMode = true
      let cFrame = this.playbook.currentFrame
      this.playbook.update()
      if (this.playbook.frames && !this.playbook.frames.length) { // 如果没有帧
        this.insertImage(cFrame)
      }
      this.playbook.onselectedchange = (e) => {
        // console.log(e.selectedItem)
        if (e.selectedItem) { // 选中物体
          // console.log(e.selectedItem.typeName)
          let selectType = e.selectedItem.typeName
          let showGraph = selectType === 'offense' || selectType === 'defense'
          if (selectType === 'line') { // 选中线段
            self.lineColor = e.selectedItem.color
            let line = e.selectedItem.shape[0]
            let lineType = e.selectedItem.shape[1]
            self.lineList.forEach(item => {
              item.selected = false
            })
            if (line === 'l') {
              self.lineList[0].selected = true
            } else {
              self.lineList[1].selected = true
            }
            self.lineTypeList.forEach(item => {
              item.selected = false
            })
            self.lineTypeList[lineType - 1].selected = true
          } else if (showGraph) { // 选中图形元素
            self.fontColor = e.selectedItem.__color
            self.graphColor = e.selectedItem.__backgroundColor
          }
          if (self.isFunctional && showGraph) {
            self.isFunctional = false
          } else if (!showGraph) {
            self.isFunctional = true
          }
        }
        if (!e.selectedItem) { // 选中球场
          if (self.selectedLineType && self.selectedLineType.id) { // 选中了线段，则清除选中状态
            self.selectedLineType = null
          }
          self.lineTypeList.forEach((item) => {
            if (item.selected) {
              item.selected = false
            }
          })
          if (!self.isFunctional) {
            self.isFunctional = true
          }
        }
      }
      // 线段绘制完成事件
      this.playbook.onaddedline = (e) => {
        self.resetLineType()
        let index = self.lineTypeList.findIndex(function (item, index, arr) {
          return item.selected
        })
        self.$set(self.lineTypeList, index, Object.assign({}, self.lineTypeList[index], {selected: false}))
        self.selectedLineType = null
      }
      // 历史重做事件
      this.playbook.onhistorychange = () => {
        self.canUndo = !self.playbook.canUndo()
        self.canRedo = !self.playbook.canRedo()
      }
    },
    // 切换帧
    switchFrame (index) {
      let frameList = [...this.frameList]
      frameList.forEach(f => {
        f.selected = false
      })
      frameList[index].selected = true
      let frame = this.playbook.currentFrame
      if (frame !== this.frame) {
        this.playContinue = !frame.pause
        frame = this.frame
        this.playbook.index = index
        this.playbook.update()
      }
      frameList[index].src = this.playbook.toDataURL(frame, 0.2)
      this.playContinue = !this.frameList[index].pause
      this.frameList = frameList
    },
    DeleteFrame (index) {
      this.$confirm('确认删除该战术板帧吗？删除后不可恢复', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.frameList.splice(index, 1)
        let frame = this.playbook.frames[index]
        this.playbook.removeFrame(frame)
        this.playbook.update()
        // this.updateScroll()
      }).catch((err) => {
        console.log(err)
      })
    },
    // 选择线段类型
    selectLineType (index) {
      this.resetLineType()
      this.lineTypeList[index].selected = true
      this.selectedLineType = this.lineTypeList[index]
      if (this.selectedLine && !this.playbook.selectedItem) {
        this.addLine()
      }
    },
    // 选择直线或曲线
    selectLine (index) {
      this.lineList.forEach((item, index) => {
        item.selected = false
      })
      this.lineList[index].selected = true
      this.selectedLine = this.lineList[index]
      if (this.selectedLineType && !this.playbook.selectedItem) {
        this.addLine()
      }
    },
    allowDrop (ev) {
      ev.preventDefault()
    },
    drop (e) {
      let pd = document.getElementById('pb')
      let canvas = pd.children[0].children[0]
      let {x, y} = getCanvasPos(canvas, e)
      // console.log('x', x, 'y', y)
      let isAttack = this.dragedObj.type === 'offense'
      let isDefense = this.dragedObj.type === 'defense'
      let text
      if (isAttack && this.attackNum >= 10) {
        text = ' '
      } else if (isDefense && this.defenseNum >= 10) {
        text = ' '
      } else {
        text = isAttack ? this.attackNum : this.defenseNum
      }
      this.playbook.addElement(this.dragedObj.type, x / this.transformScale, y / this.transformScale, {
        text: text,
        shape: this.dragedObj.shape,
        backgroundColor: this.dragedObj.backgroundColor,
        color: this.dragedObj.color
      })
      this.playbook.update()
      if (isAttack && this.attackNum <= 10) {
        this.attackNum++
      }
      if (isDefense && this.defenseNum <= 10) {
        this.defenseNum++
      }
    },
    onDragStart (event, type, bgColor) {
      // console.log('开始拖动')
      this.dragedObj = {
        type: type,
        shape: type === 'offense' ? 1 : 2,
        backgroundColor: bgColor,
        color: this.fontColor
      }
    },
    onDragEnd (e) {
      // console.log('结束拖动:', e)
    },
    onDragEnter (e) {
      // console.log('object Coming：', e)
    },
    onMouseDown (e) {
      // console.log('点击：', e)
    },
    appendFrame () {
      this.playbook.appendFrame()
      this.reset()
    },
    // 取消选中的图形
    cancelSeleted () {
      this.updateSelectedItem()
    },
    // 保存选中的图形
    saveSeletedItem () {
      if (this.playbook.selectedItem) {
        this.updateColorBgColor(this.fontColor, this.graphColor)
      }
      this.updateSelectedItem()
    },
    // 更新战术板
    updateSelectedItem () {
      this.isFunctional = true
      this.fontColor = '#fff'
      this.playbook.selectedItem = null
      this.playbook.update()
    },
    // 删除选中的图形
    handleDeleteItem () {
      if (this.playbook.selectedItem) {
        this.playbook.remove(this.playbook.selectedItem)
        this.resetLineType()
      }
      this.updateSelectedItem()
    },
    updateShape (item) {
      this.graghList.forEach((graf) => {
        if (graf.selected) {
          graf.selected = false
        }
        if (graf.id === item) {
          graf.selected = true
        }
      })
      this.playbook.selectedItem.shape = item
      this.playbook.update()
    },
    // 插入线段
    addLine () {
      this.playbook.addLine(this.selectedLine.type + this.selectedLineType.id, {color: this.lineColor})
    },
    // 插入一帧
    insertFrame () {
      let frame = this.playbook.insertFrame()
      this.insertImage(frame)
    },
    insertImage (frame) {
      var img = document.createElement('img')
      frame.image = img
      img.frame = frame
      img.src = this.playbook.toDataURL(frame, 0.2)
      let insertFrame = {
        src: img.src,
        selected: false
      }
      this.frameList.splice(this.playbook.index + 1, 0, insertFrame) // 在当前帧后面插入
      // this.updateScroll()
    },
    // 重置
    reset () {
      let line = this.playbook.cancelLine()
      if (!line) {
      }
      this.playbook.clear()
      this.playbook.update()
      let frame = this.playbook.frames[0]
      let img = new Image()
      frame.image = img
      img.frame = frame
      img.src = this.playbook.toDataURL(frame, 0.2)
      this.drawFrameList()
      this.fontColor = '#fff'
      if (this.playbook.selectedItem) {
        this.playbook.selectedItem = null
        this.playbook.update()
      }
      if (!this.isFunctional) {
        this.isFunctional = true
      }
      this.hasReset = true
    },
    saveCurrentFrame () {
      if (this.playbook.selectedItem) {
        this.playbook.selectedItem = null
      }
      let frame = this.playbook.currentFrame
      if (!this.playContinue) {
        frame.pause = true
      }
      this.playbook.serialize()
      let idx = this.playbook.index
      // console.log(this.playbook.currentFrame)
      frame.image = new Image()
      frame.image.src = this.playbook.toDataURL(frame, 0.2)
      this.frameList[idx].src = frame.image.src
      this.post(this.playbook.serialize())
    },
    updateColorBgColor (color, bgColor) {
      this.playbook.selectedItem.backgroundColor = bgColor
      this.playbook.selectedItem.color = color
    },
    // 重置线段选中状态
    resetLineType () {
      this.lineTypeList.forEach(line => {
        if (line.selected) {
          line.selected = false
        }
      })
    },
    updateLine () {
      if (this.playbook.selectedItem && this.playbook.selectedItem.typeName === 'line') {
        this.playbook.selectedItem.shape = `${this.selectedLine.type}${this.selectedLineType.id}`
        this.playbook.update()
      }
    },
    // 保存战术板整个步骤
    handleSaveSteps () {
      let content = this.playbook.serialize()
      this.post(content)
    },
    undo () {
      let line = this.playbook.cancelLine()
      if (!(line && line.shape)) { // 不是取消绘制线条
        this.playbook.undo()
        this.playbook.update()
      }
    },
    redo () {
      this.playbook.redo()
      this.playbook.update()
    },
    // 绘制帧步骤列表
    drawFrameList (hasFrame, start) {
      this.frameList = []
      if (hasFrame) {
        this.playbook.deserialize(this.tacticsInfo)
        // let stime = +new Date()
        for (let i = 0, flength = this.playbook.frames.length; i < flength; i++) {
          this.frameList.push({
            src: i > this.stepLength ? '' : this.playbook.toDataURL(this.playbook.frames[i], 0.2),
            selected: false
          })
        }
        this.lastStep = this.stepLength
        // console.log(+new Date() - stime)
        if (!start || start === 0) {
          this.frameList[0].selected = true
        }
      } else {
        let frame = this.playbook.currentFrame
        this.frameList.push({
          src: this.playbook.toDataURL(frame, 0.2),
          selected: true
        })
      }
      // this.updateScroll()
      this.playbook.update()
    },
    updateScroll () {
      this.scrollPercent = 601 / ((this.frameWidth + 11) * this.frameList.length)
      this.scrollPercent = this.scrollPercent > 1 ? 1 : this.scrollPercent
      let scrollDom = document.querySelectorAll('.el-scrollbar__thumb')[0]
      scrollDom.style.width = `${this.scrollPercent * 100}%`
    },
    drawStepFrame (start, end) {
      for (let i = start; i < end; i++) {
        if (this.frameList[i]) {
          this.frameList[i].src = this.playbook.toDataURL(this.playbook.frames[i], 0.2)
        }
      }
      this.lastStep = end
    },
    post (content, isPostToServer) {
      api.update({
        sportTypeId: this.sportType,
        tacticTypeId: this.tacticTypeId,
        id: this.tacticId,
        content: content
      }).then((res) => {
        let content = JSON.parse(this.playbook.serialize())
        this.$store.commit('TACTICS_INFO', Object.assign({}, content, {
          id: this.tacticId,
          key: Math.random().toString(36).substr(2)
        }))
      })
    }
  }
}
</script>
<style lang="scss">
@import '../../../styles/playbook.scss';
</style>
